package com.jzo2o.orders.manager.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.jzo2o.common.constants.MqConstants;
import com.jzo2o.common.model.msg.TradeStatusMsg;
import com.jzo2o.orders.manager.service.IOrdersCreateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author:on
 * @Description:监听mq获取支付结果
 * @Date Created in 2024-09-04-8:34
 * @Modified By:
 */
@Slf4j
@Component
public class TradeStatusListener {
    @Resource
    private IOrdersCreateService ordersCreateService;

    /**
     * 更新支付结果
     * 支付成功
     *
     * @param msg 消息
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MqConstants.Queues.ORDERS_TRADE_UPDATE_STATUS),
            exchange = @Exchange(name = MqConstants.Exchanges.TRADE, type = ExchangeTypes.TOPIC),
            key = MqConstants.RoutingKeys.TRADE_UPDATE_STATUS
    ))
    public void listenTradeUpdatePayStatusMsg(String msg){
        //解析消息，通过查询支付服务的源代码，消息内容是List<TradeStatusMsg>的json格式
        List<TradeStatusMsg> tradeStatusMsgs = JSON.parseArray(msg, TradeStatusMsg.class);

        //根据productAppId系统标识判断是不是自己的,家政订单的支付系统标识，是jzo2o.orders
        //还需要status为4的支付成功的结果
        List<TradeStatusMsg> collect = tradeStatusMsgs.stream().filter(item -> "jzo2o.orders".equals(item.getProductAppId()) && item.getStatusCode() == 4).collect(Collectors.toList());

        //更新数据库订单表的支付状态和订单状态
        for (TradeStatusMsg tradeStatusMsg : collect) {
            ordersCreateService.paySuccess(tradeStatusMsg);
        }

    }
}
